const Promise = require('bluebird');
const apis = {};

/**
 * 基础Api
 */
const appV1 = require('./v1/app');
const cacheV1 = require('./v1/cache');
const uploadV1 = require('./v1/upload');
const articlesV1 = require('./../public/v1/articles');
Object.assign(apis, {
    /**
     * app
     */
    '/v1/app/menu': {
        permission: true,
        handler: appV1.menu
    },
    '/v1/app/wechat_js_config': {
        handler: appV1.wechatJsConfig
    },
    /**
     * 缓存
     */
    '/v1/cache/dicts': {
        handler: cacheV1.dicts
    },
    /**
     * 图片上传
     */
    '/v1/upload/params': {
        permission: true,
        handler: uploadV1.params
    },
    '/v1/upload/ueditor': {
        permission: true,
        handler: uploadV1.ueditor
    },
    /**
     * 文章
     */
    '/v1/articles/browse': {
        handler: articlesV1.browse
    },
    '/v1/articles/load': {
        handler: articlesV1.load
    }
});

/**
 * 用户相关Api
 */
const userV1 = require('./v1/user');
Object.assign(apis, {
    /**
     * 用户
     */
    '/v1/user/login': {
        handler: userV1.login
    },
    '/v1/user/send_code': {
        handler: userV1.sendCode
    },
    '/v1/user/forgot': {
        handler: userV1.forgot
    },
    '/v1/user/register': {
        handler: userV1.register
    },
    '/v1/user/change_password': {
        permission: true,
        handler: userV1.changePassword
    },
    '/v1/user/load': {
        permission: true,
        handler: userV1.load
    },
    '/v1/user/edit': {
        permission: true,
        handler: userV1.edit
    },
    '/v1/user/validate': {
        handler: userV1.validate
    },
    '/v1/user/logout': {
        handler: userV1.logout
    },
    '/v1/user/edit_by_wechat': {
        permission: true,
        handler: userV1.editByWechat
    }
});

/**
 * 建议反馈相关Api
 */
const suggestionsV1 = require('./v1/suggestions');
Object.assign(apis, {
    /**
     * 建议反馈
     */
    '/v1/suggestions/browse': {
        handler: suggestionsV1.browse
    },
    '/v1/suggestions/load': {
        handler: suggestionsV1.load
    },
    '/v1/suggestions/add': {
        handler: suggestionsV1.add
    }
});


/**
 * 请求转发，权限控制，数据处理
 */
module.exports = function (storage) {
    return function (req, res) {
        let {path, session, body, query} = req;
        let api = apis[path];
        if (api) {
            let {handler, permission, table} = api;
            let user_id = session.user_id;
            //权限处理
            if (permission && !user_id) {
                return res.status('401').json({success: false, code: 401, message: '未登录'});
            }

            //处理post数据
            storage.controller.handleBody({req: req, model: table && (storage.models[table] || storage.modelsData[table])});

            return Promise.resolve().then(function () {
                return handler({
                    req: req, res: res, body: body, query: query, session: session, user_id: user_id
                }, storage);
            }).then(function (response) {
                return res.json(response === null ? {} : response);
            }, function (err) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                }
                return res.json({success: false, code: 500, message: err && err.message || '请求异常'});
            });
        } else {
            res.json({success: false, code: 404, message: '无效API'});
        }
    };
};